package mrpanyu.guitool.textfile;

import java.io.File;
import java.util.Base64;

import mrpanyu.guitool.base.annotation.Action;
import mrpanyu.guitool.base.annotation.OnParameterChange;
import mrpanyu.guitool.base.annotation.Parameter;
import mrpanyu.guitool.base.annotation.ToolModel;
import mrpanyu.guitool.base.model.ParameterType;
import mrpanyu.guitool.base.model.Tool;
import mrpanyu.guitool.base.util.CommonUtils;

@ToolModel(displayName = "Base64编解码", description = "Base64编码/解码功能", enableProfiles = false)
public class Base64Tool {

	@Parameter(displayName = "内容来源", type = ParameterType.SELECT, options = { "手工输入", "选择文件" }, order = 1)
	private String source = "手工输入";

	@Parameter(displayName = "输入文本", type = ParameterType.MULTILINE_TEXT, order = 2)
	private String textValue = "";

	@Parameter(displayName = "输入文件", type = ParameterType.FILE, order = 3, visible = false)
	private File inputFile;

	@Parameter(displayName = "输出文件", description = "可空，留空则输出到输出窗口", type = ParameterType.FILE, order = 4)
	private File outputFile;

	@OnParameterChange("source")
	public void onSourceChange(Tool tool) {
		if ("手工输入".equals(source)) {
			tool.getParameter("textValue").setVisible(true);
			tool.getParameter("inputFile").setVisible(false);
		} else {
			tool.getParameter("textValue").setVisible(false);
			tool.getParameter("inputFile").setVisible(true);
		}
	}

	@Action(displayName = "Base64编码", order = 1)
	public void encode(Tool tool) throws Exception {
		tool.clearMessages();
		byte[] data = null;
		if ("手工输入".equals(source)) {
			data = textValue.getBytes("UTF-8");
		} else {
			data = CommonUtils.readBytes(inputFile);
		}
		String output = Base64.getEncoder().encodeToString(data);
		if (outputFile == null) {
			tool.infoMessage(output);
		} else {
			outputFile.getParentFile().mkdirs();
			CommonUtils.writeString(outputFile, output, "UTF-8");
			tool.infoMessage("已输出到文件: " + outputFile);
			tool.infoMessage("(输出文件参数留空可输出到控制台)");
		}
	}

	@Action(displayName = "Base64解码", order = 2)
	public void decode(Tool tool) throws Exception {
		tool.clearMessages();
		String base64Text = null;
		if ("手工输入".equals(source)) {
			base64Text = textValue;
		} else {
			base64Text = CommonUtils.readString(inputFile, "UTF-8");
		}
		byte[] data = Base64.getDecoder().decode(base64Text);
		if (outputFile == null) {
			tool.infoMessage(new String(data, "UTF-8"));
		} else {
			outputFile.getParentFile().mkdirs();
			CommonUtils.writeBytes(outputFile, data);
			tool.infoMessage("已输出到文件: " + outputFile);
			tool.infoMessage("(输出文件参数留空可输出到控制台)");
		}
	}

}
